package Avanzado.net;

import java.net.*;
import java.util.*;

public class LoggerServer
{
	public static final int SERVER_TIMEOUT_MILLIS = 5000;
	
	private ServerSocket _server;
	
	private int _port;
	
	private boolean _quit = false;
	
	private ArrayList<WorkerThread> _threads = new ArrayList<WorkerThread>();
	
	public LoggerServer(int port) throws Exception
	{
	 	_server = new ServerSocket();
	 	
		_server.bind(new InetSocketAddress("127.0.0.1", port), 10);
		
		_server.setSoTimeout(LoggerServer.SERVER_TIMEOUT_MILLIS);
		
		_port = port;
	}
	
	public void loop() throws Exception
	{
		System.out.printf("Servidor escuchando en el puerto: %d\n", _port);
		
		do
		{
			try
			{
				Socket client = _server.accept(); //bloquea, pero cada 5 segs tira SocketTimeoutException
				
				WorkerThread worker = new WorkerThread(client);
				
				_threads.add(worker);				
				
				worker.start();
			}
			catch (SocketTimeoutException timeoutException)
			{
				// Timeout: limpiar los hilos terminados, ver si es hora de terminar.
				
				ArrayList<WorkerThread> joinedThreads = new ArrayList<WorkerThread>();
				
				for (WorkerThread worker : _threads)
				{
					if (worker.isDone())
					{
						worker.join();
						joinedThreads.add(worker);
					}
				}
				
				_threads.removeAll(joinedThreads);
				
			}
			
		}
		while (!_quit);
		
		for (WorkerThread worker : _threads)
		{
			worker.join();
		}
		
		_server.close();
	}
	
	
}
